package com.motu.monstercity.server.gate;


import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.ext.web.handler.CorsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import io.vertx.ext.jdbc.JDBCClient;
//import io.vertx.ext.jdbc.JDBCClient;

public class HttpVerticle extends AbstractVerticle {

    private static final Logger logger = LoggerFactory.getLogger(HttpVerticle.class);
    public static WebClient webClient;

    @Override
    public void start(Promise<Void> future) {

        webClient = WebClient.create(vertx, new WebClientOptions().setKeepAlive(true));
        startWeb(httpServer -> {
            if (httpServer.failed()) {
                httpServer.cause().printStackTrace();
                future.fail(httpServer.cause());
            } else {
                getLogger().info("----===listen port " + httpServer.result().actualPort());
                future.complete();
            }
        });

    }

    private Logger getLogger() {
        return logger;
    }

    public void startWeb(Handler<AsyncResult<HttpServer>> nextHandler) {
        //		try {
        //			Long ll = null;
        //			System.out.println("############# ll :"+ll.longValue());
        //		} catch (Exception e) {
        //			logger.error(Tool.getException(e));
        //		}

        getLogger().info(">>>>>>>>>>>>>>> startWeb");
        Router router = Router.router(vertx);
        Set<String> allowHeaders = new HashSet<>();
        allowHeaders.add("x-requested-with");
        allowHeaders.add("Access-Control-Allow-Origin");
        allowHeaders.add("origin");
        allowHeaders.add("Content-Type");
        allowHeaders.add("accept");
        router.route().handler(CorsHandler.create("*").allowedHeaders(allowHeaders).allowedMethod(HttpMethod.POST));
        router.route("/").handler(routingContext -> {
            routingContext.response().setStatusCode(200).setStatusMessage("OK").end("Gate http service is running!!");
        });

        router.get("/test/removeuser").handler(this::doRemoveUser);

        vertx.createHttpServer().requestHandler(router).listen(config().getInteger("http-port", 8044),
                config().getString("host-name", "localhost"), nextHandler::handle);

    }

    /***
     * 断开用户
     * @param routingContext
     */
    private void doRemoveUser(RoutingContext routingContext) {

        long userId = Long.parseLong(routingContext.request().getParam("userid"));

        ServerWebSocket socket = SocketManager.getSocket(userId);
        if (socket != null) {
            socket.end();
            SocketManager.removeSocket(userId, null);
            routingContext.response().end("success");
        } else {
            routingContext.response().end("has not user");
        }

    }

}
